package com.erp.ae.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.ae.domain.ImageBankParam;
import com.erp.ae.domain.enums.AliExpressInterfaceEnum;
import com.erp.ae.domain.enums.ShipsFromCountry;
import com.erp.ae.service.IAeProductService;
import com.global.iop.domain.Protocol;
import com.ruoyi.ae.api.domain.AeProductPost;
import com.ruoyi.common.core.domain.R;
import com.erp.ae.utils.AeApiUtils;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.gather.api.domain.dto.AeAutoProductDto;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商户订单Service业务层处理
 *
 * @author erp
 * @date 2023-03-09
 */
@RequiredArgsConstructor
@Service
public class IAeProductServiceImpl implements IAeProductService {

    @Override
    public String categoryTreeList(String categoryId, Long sellerId) {
        //生成参数Map
        Map<String, Object> paremeterMap = new HashMap<>();
        paremeterMap.put("category_id", categoryId);
        paremeterMap.put("only_with_permission", "true");
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(sellerId);
        String msg =
                AeApiUtils.sendRequestHttpMethodIsGet(
                        AliExpressInterfaceEnum.categoryList.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        if (msg != null) {
            return msg;
        } else {
            return "发送失败";
        }
    }

    @Override
    public R<Object> storeBrandsList(String categoryId, Long storeId) {
        Map<String, Object> paremeterMap = new HashMap<>();
        paremeterMap.put("category_id", categoryId);
        paremeterMap.put("locale", "en_US");
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(storeId);
        String msg =
                AeApiUtils.sendRequestHttpMethodIsGet(
                        AliExpressInterfaceEnum.getStorePromotionsList.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        if (msg.contains("global_seller_brands_list_response")) {
            return R.ok(msg);
        } else {
            return R.fail("请求失败");
        }
    }

    @Override
    public R<Object> onlineaeproduct(Map<String, Object> paremeterMap) {
        String sellerId = (String) paremeterMap.get("sellerId");
        //生成参数Map
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(sellerId);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.onLineAeProduct.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg != null && msg.contains("true")) {
            return R.ok(msg);
        } else {
            return R.fail("上架失败");
        }
    }

    @Override
    public R<Object> offlineAeProduct(Map<String, Object> paremeterMap) {
        String storeId = (String) paremeterMap.get("sellerId");
        //生成参数Map
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(storeId);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.offlineAeProduct.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg != null && msg.contains("true")) {
            return R.ok(msg);
        } else {
            JSONObject jsonObject = JSONObject.parseObject(msg);
            JSONObject response = jsonObject.getJSONObject("aliexpress_postproduct_redefining_offlineaeproduct_response");
            if (response == null) {
                return R.fail(jsonObject.getJSONObject("error_response").getString("msg"), "下架失败");
            }
            JSONObject result = response.getJSONObject("result");
            JSONArray jsonArray = result.getJSONObject("error_details").getJSONArray("error_detail");
            JSONObject array1 = jsonArray.getJSONObject(0);
            String error_message = array1.getString("error_message");
            // 商品不存在的话下架成功
            if ("Product does not exist".equals(error_message) || "Product is not online".equals(error_message)) {
                return R.ok(error_message, "下架成功");
            }
            return R.fail(error_message, "下架失败");
        }
    }

    @Override
    public ImageBankParam uploadImageForSDK(ImageBankParam imageBankParam) {
        //TODO 暂时写死
        String domain = "https://file.pbb2c.com/";
        String accessToken = AeApiUtils.getToken(imageBankParam.getSellerId());
        String imageUrl = imageBankParam.getImageUrl();
        String storeUserName = imageBankParam.getStoreUserName();
        if (!imageUrl.contains("https:") && !imageUrl.contains("http:")) {
            //不包含https:,说明还没上传过，需要拼接前缀
            imageUrl = domain + imageBankParam.getImageUrl();
        } else {
            //包含，跳过
            imageBankParam.setNewDraw("continue");
        }
        String resMsg = AeApiUtils.sendImageRequest(
                imageBankParam.getIsAddWatemark(),
                storeUserName,
                imageUrl,
                imageBankParam.getGroupId(),
                accessToken
        );
        if (resMsg.contains("photobank_url")) {
//            System.out.println(resMsg);
            String photobankUrl = JSONObject
                    .parseObject(resMsg)
                    .getJSONObject("aliexpress_photobank_redefining_uploadimageforsdk_response")
                    .getJSONObject("result")
                    .getString("photobank_url");
            imageBankParam.setNewDraw(photobankUrl);
            return imageBankParam;
        }else {
            return null;
        }
    }

    @Override
    public R<Object> uploadProductTest(Map<String, Object> map) {
        Map<String, Object> paremeterMap = new HashMap<>();
        String accessToken = AeApiUtils.getToken(map.get("storeId").toString());
        //转Json
        JSONObject json = new JSONObject(map);
        System.out.println(json);
        paremeterMap.put("aeop_a_e_product", json);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.productPost.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg.contains("error_response")) {
            return R.fail(msg);
        } else {
            return R.ok(msg);
        }
    }

    @Override
    public Map<String, Object> getEUResponsiblePersonFromAe(Long categoryId, Long sellerId) {
        //生成参数Map
        Map<String, Object> paremeterMap = new HashMap<>();
        paremeterMap.put("category_id", categoryId);
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(sellerId);
        String msg =
                AeApiUtils.sendRequestHttpMethodIsGet(
                        AliExpressInterfaceEnum.getEUResponsiblePerson.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        paremeterMap = new HashMap<>();
        if (msg.contains("aliexpress_category_eu_responsible_persons_list_response")) {
            System.out.println(msg);
            String support = JSONObject.parseObject(msg)
                    .getJSONObject("aliexpress_category_eu_responsible_persons_list_response")
                    .getString("support");
            if (support.equals("false")) {
                //说明没有欧盟负责人
                paremeterMap.put("support", false);
                paremeterMap.put("code", 500);

            } else {
                //获取欧盟负责人列表
                if (!msg.contains("eu_contact_module")) {
                    paremeterMap.put("support", false);
                    paremeterMap.put("code", 500);
                } else {
                    //有欧盟负责人
                    List<Dict> personList = JsonUtils.parseArrayMap(JSONObject.parseObject(msg)
                            .getJSONObject("aliexpress_category_eu_responsible_persons_list_response")
                            .getJSONObject("eu_contact_module_list")
                            .getString("eu_contact_module"));
                    for (Dict dict : personList) {
                        if (dict.get("msr_eu_id").equals(-2)) {
                            continue;
                        }
                        paremeterMap = new HashMap<>();
                        paremeterMap.put("msr_eu_id", dict.get("msr_eu_id"));
                        paremeterMap.put("name", dict.get("name"));
                        paremeterMap.put("support", true);
                        paremeterMap.put("code", 200);
                        return paremeterMap;
                    }
                }
            }
        }
        paremeterMap.put("support", false);
        paremeterMap.put("code", 500);
        return paremeterMap;
    }

    @Override
    public R<Object> queryPromiseTemplateById(Integer templateId, Long storeId) {
        //生成参数Map
        Map<String, Object> paremeterMap = new HashMap<>();
        paremeterMap.put("template_id", templateId);
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(storeId);
        String templateList =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.queryPromiseTemplateById.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        if (templateList != null) {
            System.out.println(templateList);
            JSONArray result = JSONArray.parseArray(JSONObject.parseObject(templateList).getJSONObject("aliexpress_postproduct_redefining_querypromisetemplatebyid_response").getJSONObject("result").getJSONObject("template_list").getString("templatelist"));
            return R.ok(result.toJSONString());
        } else {
            return R.fail("发送失败");
        }
    }

    @Override
    public R<Object> getFreightTemplateLogisticsCompany(Map<String, Object> map) {
        //平台店铺id
        Long storeId = (Long) map.get("storeId");
        Long templateId = (Long) map.get("templateId");
        //生成参数Map
        Map<String, Object> paremeterMap = new HashMap<>();
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(storeId);
        paremeterMap.put("template_id", templateId);
        String returnMsg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.getFreightSettingByTemplateQuery.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(returnMsg);
        JSONObject returnObject = JSONObject.parseObject(returnMsg);
        StringBuffer logisticsCompanyStringBuffer = new StringBuffer();
        //保存该信息至平台运费模板表
        if (returnMsg.contains("error_desc")) {
            return R.fail("请求失败");
        } else {
            String aeopFreightSetting = returnObject
                    .getJSONObject("aliexpress_freight_redefining_getfreightsettingbytemplatequery_response")
                    .getJSONObject("freight_setting_list")
                    .getString("aeop_freight_setting");
            JSONArray aeopFreightSettingArr = JSONArray.parseArray(aeopFreightSetting);
            for (Object freightSetting : aeopFreightSettingArr) {
                JSONObject template = (JSONObject) freightSetting;
                String logisticsCompany = template.getJSONObject("template").getString("logistics_company");
                if (logisticsCompany.contains("OTHER_") || logisticsCompany.contains("Other_")) {
                    //如果包含 自定义，则放入List
                    String country = logisticsCompany.substring(6, logisticsCompany.length());
                    logisticsCompanyStringBuffer.append(country);
                    logisticsCompanyStringBuffer.append(",");
                }

            }
            return R.ok(logisticsCompanyStringBuffer);
        }
    }

    @Override
    public R<Object> getSellerStoreFreightTemplate(Long sellerId) {
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(sellerId);
        String returnMsg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.listFreightTemplate.getCode(),
                        Protocol.TOP,
                        accessToken
                );
        JSONObject returnObject = JSONObject.parseObject(returnMsg).getJSONObject("aliexpress_freight_redefining_listfreighttemplate_response");
        if (returnObject.getString("result_success").equals("false")) {
            return R.fail("请求失败");
        } else {
            return R.ok(returnObject.toJSONString());
        }
    }

    @Override
    public R<Object> queryAeProduct(Long productId, String sellerId) {
        String accessToken = AeApiUtils.getToken(sellerId);
        if (StringUtils.isEmpty(accessToken)) {
            return R.fail("店铺授权失效");
        }
        Map<String, Object> paremeterMap = new HashMap<>();
        paremeterMap.put("product_id", productId);
        String returnMsg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.queryProduct.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(returnMsg);
        if (returnMsg.contains("aliexpress_offer_product_query_response")){
            return R.ok(returnMsg);
        }else {
            JSONObject object = JSONObject.parseObject(returnMsg);
            return R.fail(object.getJSONObject("error_response").getString("sub_msg"));
        }
    }

    @Override
    public R<Object> getchildattributesresultbypostcateidandpath(String param1, String sellerId) {
        String accessToken = AeApiUtils.getToken(sellerId);

        Map<String, Object> paremeterMap = new HashMap<>();
        paremeterMap.put("locale", "en_US");
        paremeterMap.put("param1", param1);
//        request.addApiParameter("channel", "AE_GLOBAL");
//        request.addApiParameter("locale", "en_US");
//        request.addApiParameter("product_type", "2");
//        request.addApiParameter("channel_seller_id", "2671514005");
//        request.addApiParameter("param2", "219=9441741844");
        String returnMsg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.getChildAttributesResultByPostCateIdAndPath.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(returnMsg);
        return R.ok(returnMsg);
    }

    @Override
    public R<Object> findAeProductById(Map<String, Object> map) {
        String accessToken = AeApiUtils.getToken((String) map.get("storeId"));
        Long productId = (Long) map.get("productId");
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.findAeProductById.getCode(),
                        "product_id",
                        productId.toString(),
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg.contains("aliexpress_postproduct_redefining_findaeproductbyid_response")) {
//            String freightTemplateId = JSONObject.parseObject(msg).getJSONObject("aliexpress_postproduct_redefining_findaeproductbyid_response").getJSONObject("result").getString("freight_template_id");
            return R.ok(msg);
        } else {
            return R.fail("未查找到");
        }
    }

    @Override
    public R<Object> productEdit(AeProductPost aeProductPost) {
        Map<String, Object> paremeterMap = new HashMap<>();
        String accessToken = AeApiUtils.getToken(aeProductPost.getSellerId());
        if (ObjectUtils.isNull(accessToken)) {
            return R.fail(501, "店铺" + aeProductPost.getSellerId() + "授权失效");
        }
        //主体部分
        Map<String, Object> map = new HashMap<>();

        if (ObjectUtils.isNotEmpty(aeProductPost.getPostType())) {
            if (aeProductPost.getPostType() == 6) {
                HashMap<String, Object> extParamMap = new HashMap<>();
                extParamMap.put("edit_reason", "edit_by_isv");
                map.put("ext_param", extParamMap);
            }
        }

        map.put("product_id", aeProductPost.getAeProductId());
        map.put("delivery_time", aeProductPost.getDelivery_time());
        map.put("locale", "en_US");
//        map.put("base_unit", aeProductPost.getBase_unit());
//        //币种
        if (aeProductPost.getCurrency_code() != null) {
            map.put("currency_code", aeProductPost.getCurrency_code());
        } else {
            map.put("currency_code", "USD");
        }
        map.put("is_pack_sell", aeProductPost.getIs_pack_sell());
        map.put("gross_weight", aeProductPost.getGross_weight());
        map.put("package_type", aeProductPost.getPackage_type());
        map.put("package_width", aeProductPost.getPackage_width());
        map.put("package_height", aeProductPost.getPackage_height());
        map.put("package_length", aeProductPost.getPackage_length());
        map.put("add_unit", aeProductPost.getAdd_unit());
        map.put("add_weight", aeProductPost.getAdd_weight());
        map.put("reduce_strategy", aeProductPost.getReduce_strategy());
        map.put("freight_template_id", aeProductPost.getFreight_template_id());
        map.put("promise_template_id", aeProductPost.getPromis_template_id());
        if (aeProductPost.getImage_u_r_ls() == null) {
            map.put("image_u_r_ls", "[]");
        } else {
            map.put("image_u_r_ls", aeProductPost.getImage_u_r_ls());
        }
        map.put("category_id", aeProductPost.getCategory_id());
        map.put("lot_num", aeProductPost.getLot_num());
        map.put("ws_valid_num", aeProductPost.getWs_valid_num());
//        //商品多语言标题
        map.put("subject_list", aeProductPost.getSubject_list());
//        //detail_source_list 商品详描
        map.put("detail_source_list", aeProductPost.getDetail_source_list());

        //aeop_ae_product_s_k_us sku信息 + 区域定价
        if (aeProductPost.getShipsFromCountry() == null) {
            //没有海外仓
            map.put("aeop_ae_product_s_k_us", aeProductPost.getAeop_ae_product_s_k_us());
            if (ObjectUtils.isNotEmpty(aeProductPost.getAeop_national_quote_configuration())) {
                String configuration = aeProductPost.getAeop_national_quote_configuration().replace("\\", "");
                AeProductPost.AeopNationalQuoteConfiguration ational_quote_configuration = new AeProductPost.AeopNationalQuoteConfiguration();
                ational_quote_configuration.setConfiguration_data(configuration);
                ational_quote_configuration.setConfiguration_type("absolute");
                map.put("aeop_national_quote_configuration", ational_quote_configuration);
            }
        } else {
            //有海外仓
            //重新补齐skuList
            List<AeProductPost.AeopAeProductSKUs> productNewSkuList = new ArrayList<>();
            Map<String, Object> shipsFromCountryMap = ShipsFromCountry.getShipsFromCountryMap();
            List<String> shipsFromCountryList = new ArrayList<String>(Arrays.asList(aeProductPost.getShipsFromCountry().split(",")));
            if (ObjectUtils.isNotEmpty(shipsFromCountryList)) {
                shipsFromCountryList.add("CN");
            }
            List<AeProductPost.AeopAeProductSKUs> productSkuList = aeProductPost.getAeop_ae_product_s_k_us();
            for (String country : shipsFromCountryList) {
                String countryCode = (String) shipsFromCountryMap.get(country);
                String id = ";" + "200007763:" + countryCode;
                for (AeProductPost.AeopAeProductSKUs productSku : productSkuList) {
                    AeProductPost.AeopAeProductSKUs productNewSku = BeanUtil.toBean(productSku, AeProductPost.AeopAeProductSKUs.class);
                    productNewSku.setId(productNewSku.getId() + id);
                    List<AeProductPost.AeopSKUProperty> aeopSKUpropertyList = productNewSku.getAeop_s_k_u_property();
                    AeProductPost.AeopSKUProperty aeopSKUProperty = new AeProductPost.AeopSKUProperty();
                    aeopSKUProperty.setSku_property_id("200007763");
                    aeopSKUProperty.setProperty_value_id(countryCode);
                    aeopSKUpropertyList.add(aeopSKUProperty);

                    productNewSkuList.add(productNewSku);
                }
            }

            map.put("aeop_ae_product_s_k_us", productNewSkuList);

            //区域定价增加新id
            if (ObjectUtils.isNotEmpty(aeProductPost.getAeop_national_quote_configuration())) {
                String configuration = aeProductPost.getAeop_national_quote_configuration().replace("\\", "");
                AeProductPost.AeopNationalQuoteConfiguration ational_quote_configuration = new AeProductPost.AeopNationalQuoteConfiguration();

                JSONArray testArray = JSONArray.parseArray(configuration);
                for (int i = 0; i < testArray.size(); i++) {
                    JSONObject jsonObject = testArray.getJSONObject(i);
                    String absoluteQuote = jsonObject.getString("absoluteQuoteMap");
                    Map<String, Object> absoluteQuoteMap = JSON.parseObject(absoluteQuote, Map.class);
                    Map<String, Object> absoluteQuoteNewMap = new HashMap<>();
                    for (String country : shipsFromCountryList) {
                        String countryCode = (String) shipsFromCountryMap.get(country);
                        String id = ";" + "200007763:" + countryCode;
                        for (String key : absoluteQuoteMap.keySet()) {
                            BigDecimal value = (BigDecimal) absoluteQuoteMap.get(key);
                            absoluteQuoteNewMap.put(key + id, value);
                        }
                    }

                    jsonObject.remove("absoluteQuoteMap");
                    jsonObject.put("absoluteQuoteMap", absoluteQuoteNewMap);
                    ational_quote_configuration.setConfiguration_data(testArray.toJSONString());
                    ational_quote_configuration.setConfiguration_type("absolute");
                    map.put("aeop_national_quote_configuration", ational_quote_configuration);
                }
            }

        }

//        //aeop_ae_product_propertys 产品属性
        map.put("aeop_ae_product_propertys", aeProductPost.getAeop_ae_product_propertys());
        map.put("msr_eu_id", aeProductPost.getMsr_eu_id());

        JSONArray jsonArray = JSONArray.parseArray(aeProductPost.getAeop_qualification_struct_list());
        if (ObjectUtils.isNotEmpty(jsonArray)) {
            List<AeProductPost.AeopQualificationStruct> qualificationList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                AeProductPost.AeopQualificationStruct qualification = new AeProductPost.AeopQualificationStruct();
                qualification.setKey(jsonObject.getString("key"));
                qualification.setValue(jsonObject.getString("value"));
                qualificationList.add(qualification);
            }
//        map.put("aeop_qualification_struct_list", aeProductPost.getAeop_qualification_struct_list());
            map.put("aeop_qualification_struct_list", qualificationList);
        }


//        //营销图和白底图
        map.put("market_images", aeProductPost.getMarket_images());
//        map.put("aeop_a_e_multimedia", aeProductPost.getAeop_a_e_multimedia());
        //转Json
        JSONObject json = new JSONObject(map);
        System.out.println(json);
        paremeterMap.put("aeop_a_e_product", json);

        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.productEdit.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg.contains("error_response")) {
            return R.fail(msg);
        } else {
            return R.ok(msg);
        }
    }

    @Override
    public R<Object> findAeProductStatusById(Long aeProductId, Long storeId) {
        String accessToken = AeApiUtils.getToken(storeId);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.findAeProductStatusById.getCode(),
                        "product_id",
                        aeProductId.toString(),
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (!msg.contains("error_message")) {
//            String freightTemplateId = JSONObject.parseObject(msg).getJSONObject("aliexpress_postproduct_redefining_findaeproductbyid_response").getJSONObject("result").getString("freight_template_id");
            String status = JSONObject.parseObject(msg).getJSONObject("aliexpress_postproduct_redefining_findaeproductstatusbyid_response").getJSONObject("result").getString("status");
            return R.ok(status);
        } else {
            return R.fail(msg);
        }
    }

    @Override
    public R<Object> queryCategoryQualificationList(Long categoryId, Long sellerId) {
        String accessToken = AeApiUtils.getToken(sellerId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("category_id", categoryId);
        map.put("local", "zh_CN");
        String msg =
                AeApiUtils.sendRequestHttpMethodIsGet(
                        AliExpressInterfaceEnum.categoryQualificationsList.getCode(),
                        map,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg.contains("aliexpress_category_qualifications_list_response")) {
            return R.ok(msg);
        } else {
            return R.fail("未查找到");
        }
    }

    @Override
    public R<Object> editSimpleProductFiled(Map<String, Object> map) {
        String accessToken = AeApiUtils.getToken((Long) map.get("storeId"));
        map.remove("storeId");
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.editSimpleProductFiled.getCode(),
                        map,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg.contains("aliexpress_postproduct_redefining_editsimpleproductfiled_response")) {
            return R.ok();
        } else {
            return R.fail("未查找到");
        }
    }

    @Override
    public R<Object> getErpProductInfo(AeProductPost aeProductPost) {
        Map<String, Object> paremeterMap = new HashMap<>();
        String accessToken = AeApiUtils.getToken(aeProductPost.getSellerId());
        //主体部分
        Map<String, Object> map = new HashMap<>();
        map.put("delivery_time", aeProductPost.getDelivery_time());
        map.put("locale", "en_US");
        map.put("base_unit", aeProductPost.getBase_unit());
        //币种
        if (aeProductPost.getCurrency_code() != null) {
            map.put("currency_code", aeProductPost.getCurrency_code());
        } else {
            map.put("currency_code", "USD");
        }
        map.put("is_pack_sell", aeProductPost.getIs_pack_sell());
        map.put("gross_weight", aeProductPost.getGross_weight());
        map.put("package_type", aeProductPost.getPackage_type());
        map.put("package_width", aeProductPost.getPackage_width());
        map.put("package_height", aeProductPost.getPackage_height());
        map.put("package_length", aeProductPost.getPackage_length());
        map.put("add_unit", aeProductPost.getAdd_unit());
        map.put("add_weight", aeProductPost.getAdd_weight());
        map.put("reduce_strategy", aeProductPost.getReduce_strategy());
        map.put("freight_template_id", aeProductPost.getFreight_template_id());
        map.put("promise_template_id", aeProductPost.getPromis_template_id());
        if (aeProductPost.getImage_u_r_ls() == null) {
            map.put("image_u_r_ls", "[]");
        } else {
            map.put("image_u_r_ls", aeProductPost.getImage_u_r_ls());
        }
        map.put("category_id", aeProductPost.getCategory_id());
        map.put("lot_num", aeProductPost.getLot_num());
        map.put("ws_valid_num", aeProductPost.getWs_valid_num());
        //商品多语言标题
        map.put("subject_list", aeProductPost.getSubject_list());
        //detail_source_list 商品详描
        map.put("detail_source_list", aeProductPost.getDetail_source_list());

        //aeop_ae_product_s_k_us sku信息
        if (aeProductPost.getShipsFromCountry() == null) {
            //没有海外仓
//        String strTest = "[{\"aeop_s_k_u_property\":[{\"property_value_definition_name\":\"Dinosaur Car\",\"property_value_id\":\"10\",\"sku_image\":\"https://ae01.alicdn.com/kf/S179878f8ae324d9dbc8ec53646f8ad2bX.jpg\",\"sku_property_id\":\"14\"},{\"property_value_id\":\"201336101\",\"sku_property_id\":\"200007763\"}],\"currency_code\":\"USD\",\"id\":\"14:10;200007763:201336101\",\"ipm_sku_stock\":1,\"sku_code\":\"PB1650053486061264896\",\"sku_price\":\"38.55\",\"sku_stock\":\"true\"},{\"aeop_s_k_u_property\":[{\"property_value_definition_name\":\"Dinosaur Car\",\"property_value_id\":\"10\",\"sku_image\":\"https://ae01.alicdn.com/kf/S179878f8ae324d9dbc8ec53646f8ad2bX.jpg\",\"sku_property_id\":\"14\"},{\"property_value_id\":\"201336100\",\"sku_property_id\":\"200007763\"}],\"currency_code\":\"USD\",\"id\":\"14:10;200007763:201336100\",\"ipm_sku_stock\":1,\"sku_code\":\"PB1650053486061264896\",\"sku_price\":\"36.56\",\"sku_stock\":\"true\"},{\"aeop_s_k_u_property\":[{\"property_value_definition_name\":\"Dinosaur Car\",\"property_value_id\":\"10\",\"sku_image\":\"https://ae01.alicdn.com/kf/S179878f8ae324d9dbc8ec53646f8ad2bX.jpg\",\"sku_property_id\":\"14\"},{\"property_value_id\":\"201336342\",\"sku_property_id\":\"200007763\"}],\"currency_code\":\"USD\",\"id\":\"14:10;200007763:201336342\",\"ipm_sku_stock\":1,\"sku_code\":\"PB1650053486061264896\",\"sku_price\":\"36.56\",\"sku_stock\":\"true\"},{\"aeop_s_k_u_property\":[{\"property_value_definition_name\":\"car\",\"property_value_id\":\"29\",\"sku_image\":\"https://ae01.alicdn.com/kf/S8c7876f7b33449bf8bde13f89452181ah.jpg\",\"sku_property_id\":\"14\"},{\"property_value_id\":\"201336101\",\"sku_property_id\":\"200007763\"}],\"currency_code\":\"USD\",\"id\":\"14:29;200007763:201336101\",\"ipm_sku_stock\":1,\"sku_code\":\"PB1650053486438752256\",\"sku_price\":\"36.56\",\"sku_stock\":\"true\"},{\"aeop_s_k_u_property\":[{\"property_value_definition_name\":\"car\",\"property_value_id\":\"29\",\"sku_image\":\"https://ae01.alicdn.com/kf/S8c7876f7b33449bf8bde13f89452181ah.jpg\",\"sku_property_id\":\"14\"},{\"property_value_id\":\"201336100\",\"sku_property_id\":\"200007763\"}],\"currency_code\":\"USD\",\"id\":\"14:29;200007763:201336100\",\"ipm_sku_stock\":1,\"sku_code\":\"PB1650053486438752256\",\"sku_price\":\"36.56\",\"sku_stock\":\"true\"},{\"aeop_s_k_u_property\":[{\"property_value_definition_name\":\"car\",\"property_value_id\":\"29\",\"sku_image\":\"https://ae01.alicdn.com/kf/S8c7876f7b33449bf8bde13f89452181ah.jpg\",\"sku_property_id\":\"14\"},{\"property_value_id\":\"201336342\",\"sku_property_id\":\"200007763\"}],\"currency_code\":\"USD\",\"id\":\"14:29;200007763:201336342\",\"ipm_sku_stock\":1,\"sku_code\":\"PB1650053486438752256\",\"sku_price\":\"36.56\",\"sku_stock\":\"true\"}]";
//        List<AeProductPost.AeopAeProductSKUs> strList = JSONArray.parseArray(strTest, AeProductPost.AeopAeProductSKUs.class);
//        map.put("aeop_ae_product_s_k_us", strList);
            map.put("aeop_ae_product_s_k_us", aeProductPost.getAeop_ae_product_s_k_us());
            if (aeProductPost.getProductType() == 1) {
                //不为3.0的品，则上传区域调价
                if (ObjectUtils.isNotEmpty(aeProductPost.getAeop_national_quote_configuration())) {
                    String configuration = aeProductPost.getAeop_national_quote_configuration().replace("\\", "");
                    AeProductPost.AeopNationalQuoteConfiguration ational_quote_configuration = new AeProductPost.AeopNationalQuoteConfiguration();
                    ational_quote_configuration.setConfiguration_data(configuration);
                    ational_quote_configuration.setConfiguration_type("absolute");
                    map.put("aeop_national_quote_configuration", ational_quote_configuration);
                }
            }

        } else {
            //有海外仓
            //重新补齐skuList
            List<AeProductPost.AeopAeProductSKUs> productNewSkuList = new ArrayList<>();
            Map<String, Object> shipsFromCountryMap = ShipsFromCountry.getShipsFromCountryMap();
            List<String> shipsFromCountryList = new ArrayList<String>(Arrays.asList(aeProductPost.getShipsFromCountry().split(",")));
            if (ObjectUtils.isNotEmpty(shipsFromCountryList)) {
                shipsFromCountryList.add("CN");
            }
            List<AeProductPost.AeopAeProductSKUs> productSkuList = aeProductPost.getAeop_ae_product_s_k_us();
            List<String> skuPropertyIdList = new ArrayList<>();
            for (String country : shipsFromCountryList) {
                String countryCode = (String) shipsFromCountryMap.get(country);
                String id = ";" + "200007763:" + countryCode;
                for (AeProductPost.AeopAeProductSKUs productSku : productSkuList) {
                    AeProductPost.AeopAeProductSKUs productNewSku = BeanUtil.toBean(productSku, AeProductPost.AeopAeProductSKUs.class);
                    String newId = productNewSku.getId() + id;
                    productNewSku.setId(productNewSku.getId() + id);
                    List<AeProductPost.AeopSKUProperty> aeopSKUpropertyList = productNewSku.getAeop_s_k_u_property();
                    AeProductPost.AeopSKUProperty aeopSKUProperty = new AeProductPost.AeopSKUProperty();
                    aeopSKUProperty.setSku_property_id("200007763");
                    aeopSKUProperty.setProperty_value_id(countryCode);
                    aeopSKUpropertyList.add(aeopSKUProperty);

                    productNewSkuList.add(productNewSku);
                    skuPropertyIdList.add(newId);
                }
            }
            map.put("aeop_ae_product_s_k_us", productNewSkuList);

            if (aeProductPost.getProductType() == 1) {
                //不为3.0的品，则上传区域调价
                //区域定价增加新id
                if (ObjectUtils.isNotEmpty(aeProductPost.getAeop_national_quote_configuration())) {
                    String configuration = aeProductPost.getAeop_national_quote_configuration().replace("\\", "");
                    AeProductPost.AeopNationalQuoteConfiguration ational_quote_configuration = new AeProductPost.AeopNationalQuoteConfiguration();

                    JSONArray testArray = JSONArray.parseArray(configuration);
                    for (int i = 0; i < testArray.size(); i++) {
                        JSONObject jsonObject = testArray.getJSONObject(i);
                        String absoluteQuote = jsonObject.getString("absoluteQuoteMap");
                        Map<String, Object> absoluteQuoteMap = JSON.parseObject(absoluteQuote, Map.class);
                        Map<String, Object> absoluteQuoteNewMap = new HashMap<>();
                        for (String country : shipsFromCountryList) {
                            String countryCode = (String) shipsFromCountryMap.get(country);
                            String id = ";" + "200007763:" + countryCode;
                            for (String key : absoluteQuoteMap.keySet()) {
                                BigDecimal value = (BigDecimal) absoluteQuoteMap.get(key);
                                absoluteQuoteNewMap.put(key + id, value);
                            }
                        }

                        jsonObject.remove("absoluteQuoteMap");
                        jsonObject.put("absoluteQuoteMap", absoluteQuoteNewMap);
                        ational_quote_configuration.setConfiguration_data(testArray.toJSONString());
                        ational_quote_configuration.setConfiguration_type("absolute");
                        map.put("aeop_national_quote_configuration", ational_quote_configuration);
                    }
                }
            }
        }


        //aeop_ae_product_propertys 产品属性
        map.put("aeop_ae_product_propertys", aeProductPost.getAeop_ae_product_propertys());

        map.put("msr_eu_id", aeProductPost.getMsr_eu_id());

        map.put("aeop_qualification_struct_list", aeProductPost.getAeop_qualification_struct_list());

        //营销图和白底图
        map.put("market_images", aeProductPost.getMarket_images());
        map.put("aeop_a_e_multimedia", aeProductPost.getAeop_a_e_multimedia());
        //转Json
        JSONObject json = new JSONObject(map);
        System.out.println("————————————————————————————————————————————");
//        System.out.println(json);


        paremeterMap.put("aeop_a_e_product", json);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.productPost.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg.contains("error_response")) {
            return R.fail(msg);
        } else {
            return R.ok(msg);
        }
    }

    @Override
    public R<Object> pageQueryProblem(Map<String, Object> map) {
        String accessToken = AeApiUtils.getToken((String) map.get("storeId"));

        String problemTypeList = "maketing_imgs_3_4,lack_white_image,lack_mobile_desc,title_abuse";
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("current_page", (Integer) map.get("current_page"));
        sendMap.put("page_size", (Integer) map.get("page_size"));
        sendMap.put("problem_type_list", problemTypeList);
        sendMap.put("operate_status", 0);

        System.out.println(sendMap);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.pageQueryProblem.getCode(),
                        sendMap,
                        Protocol.TOP,
                        accessToken
                );

        System.out.println(msg);

        return R.ok(msg);
    }

    /**
     * 用于测试发布
     *
     * @param sellerStoreProductIds
     * @param type
     * @return
     */
    @Override
    public R<Object> productOfflineForUpdateTest(String sellerStoreProductIds, Long storeId, Integer type) {
        Map<String, Object> returnMap = new HashMap<>();
        ResponseEntity<String> forEntity = null;
        String body = null;
        returnMap.put("product_ids", sellerStoreProductIds);
        returnMap.put("sellerId", storeId);
        R<Object> objectR = offlineAeProduct(returnMap);
        body = (String) objectR.getData();
        Integer code = JSONObject.parseObject(body).getInteger("code");
        if (code == 200) {
            Integer modifyCount = JSONObject.parseObject(body).getJSONObject("msg").getJSONObject("aliexpress_postproduct_redefining_offlineaeproduct_response")
                    .getJSONObject("result").getInteger("modify_count");
            return R.ok("下架成功");
        } else {
            return R.fail("下架失败");
        }
    }

    /**
     * 删除商品
     * @param productId
     * @param storeId
     * @return
     */
    @Override
    public R<Object> deleteProduct(Long productId, Long storeId) {
        //生成参数Map
        Map<String, Object> paremeterMap = new HashMap<>();
        paremeterMap.put("product_id", productId);
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(storeId);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.deleteProduct.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg.contains("sub_msg")) {
            return R.fail(msg);
        } else {
            return R.ok(msg);
        }
    }

    /**
     * 自动化上品发布方法
     *
     * @param aeAutoProductDto
     * @return
     */
    @Override
    public R<Object> autoPublishToAe(AeAutoProductDto aeAutoProductDto) {
        Map<String, Object> paremeterMap = new HashMap<>();
        String accessToken = AeApiUtils.getToken(aeAutoProductDto.getStoreId());
        //主体部分
        Map<String, Object> map = new HashMap<>();
        map.put("delivery_time", aeAutoProductDto.getDeliveryTime());
        map.put("locale", "en_US");
        map.put("base_unit", aeAutoProductDto.getBaseUnit());
        //币种
        if (aeAutoProductDto.getCurrencyCode() != null) {
            map.put("currency_code", aeAutoProductDto.getCurrencyCode());
        } else {
            map.put("currency_code", "USD");
        }
        map.put("is_pack_sell", aeAutoProductDto.getIsPackSell());
        map.put("gross_weight", aeAutoProductDto.getGrossWeight());
        map.put("package_type", aeAutoProductDto.getPackageType());
        map.put("package_width", aeAutoProductDto.getPackageWidth());
        map.put("package_height", aeAutoProductDto.getPackageHeight());
        map.put("package_length", aeAutoProductDto.getPackageLength());
        map.put("add_unit", aeAutoProductDto.getAddUnit());
        map.put("add_weight", aeAutoProductDto.getAddWeight());
        map.put("reduce_strategy", aeAutoProductDto.getReduceStrategy());
        map.put("freight_template_id", aeAutoProductDto.getFreightTemplateId());
        map.put("promise_template_id", aeAutoProductDto.getPromiseTemplateId());
        if (aeAutoProductDto.getImageURLs() == null) {
            map.put("image_u_r_ls", "[]");
        } else {
            map.put("image_u_r_ls", aeAutoProductDto.getImageURLs());
        }
        map.put("category_id", aeAutoProductDto.getCategoryId());
        map.put("lot_num", aeAutoProductDto.getLotNum());
        //商品有效天数 暂时去掉
//        map.put("ws_valid_num", aeAutoProductDto.getWs_valid_num());
        //商品多语言标题
        map.put("subject_list", aeAutoProductDto.getSubjectList());
        //detail_source_list 商品详描
        map.put("detail_source_list", aeAutoProductDto.getDetailSourceList());

        //aeop_ae_product_s_k_us sku信息
        if (aeAutoProductDto.getShipsFromCountry() == null) {
            //没有海外仓
            map.put("aeop_ae_product_s_k_us", aeAutoProductDto.getAeopAeProductSKus());
            if (aeAutoProductDto.getProductType() == 1) {
                //不为3.0的品，则上传区域调价
                if (ObjectUtils.isNotEmpty(aeAutoProductDto.getAeopNationalQuoteConfiguration())) {
                    String configuration = aeAutoProductDto.getAeopNationalQuoteConfiguration().replace("\\", "");
                    AeProductPost.AeopNationalQuoteConfiguration ational_quote_configuration = new AeProductPost.AeopNationalQuoteConfiguration();
                    ational_quote_configuration.setConfiguration_data(configuration);
                    ational_quote_configuration.setConfiguration_type("absolute");
                    map.put("aeop_national_quote_configuration", ational_quote_configuration);
                }
            }

        } else {
            //有海外仓
            //重新补齐skuList
            JSONArray productNewSkuList = new JSONArray();
            Map<String, Object> shipsFromCountryMap = ShipsFromCountry.getShipsFromCountryMap();
            List<String> shipsFromCountryList = new ArrayList<String>(Arrays.asList(aeAutoProductDto.getShipsFromCountry().split(",")));
            if (ObjectUtils.isNotEmpty(shipsFromCountryList)) {
                shipsFromCountryList.add("CN");
            }
            JSONArray productSkuList = aeAutoProductDto.getAeopAeProductSKus();
            List<String> skuPropertyIdList = new ArrayList<>();
            for (String country : shipsFromCountryList) {
                String countryCode = (String) shipsFromCountryMap.get(country);
                String id = ";" + "200007763:" + countryCode;
                for (Object productSku : productSkuList) {
                    JSONObject sku = (JSONObject) productSku;
                    JSONObject productNewSku = sku;
                    String newId = productNewSku.get("id") + id;
                    productNewSku.put("id", newId);
                    JSONArray aeopSkuPropertyList = JSONArray.parseArray(JSON.toJSONString(productNewSku.get("aeop_s_k_u_property")));
                    JSONObject aeopSkuProperty = new JSONObject();
                    aeopSkuProperty.put("sku_property_id", "200007763");
                    aeopSkuProperty.put("property_value_id", countryCode);
                    aeopSkuPropertyList.add(aeopSkuProperty);

                    productNewSkuList.add(productNewSku);
                    skuPropertyIdList.add(newId);
                }
            }
            map.put("aeop_ae_product_s_k_us", productNewSkuList);

            if (aeAutoProductDto.getProductType() == 1) {
                //不为3.0的品，则上传区域调价
                //区域定价增加新id
                if (ObjectUtils.isNotEmpty(aeAutoProductDto.getAeopNationalQuoteConfiguration())) {
                    String configuration = aeAutoProductDto.getAeopNationalQuoteConfiguration().replace("\\", "");
                    AeProductPost.AeopNationalQuoteConfiguration ational_quote_configuration = new AeProductPost.AeopNationalQuoteConfiguration();

                    JSONArray testArray = JSONArray.parseArray(configuration);
                    for (int i = 0; i < testArray.size(); i++) {
                        JSONObject jsonObject = testArray.getJSONObject(i);
                        String absoluteQuote = jsonObject.getString("absoluteQuoteMap");
                        Map<String, Object> absoluteQuoteMap = JSON.parseObject(absoluteQuote, Map.class);
                        Map<String, Object> absoluteQuoteNewMap = new HashMap<>();
                        for (String country : shipsFromCountryList) {
                            String countryCode = (String) shipsFromCountryMap.get(country);
                            String id = ";" + "200007763:" + countryCode;
                            for (String key : absoluteQuoteMap.keySet()) {
                                BigDecimal value = (BigDecimal) absoluteQuoteMap.get(key);
                                absoluteQuoteNewMap.put(key + id, value);
                            }
                        }

                        jsonObject.remove("absoluteQuoteMap");
                        jsonObject.put("absoluteQuoteMap", absoluteQuoteNewMap);
                        ational_quote_configuration.setConfiguration_data(testArray.toJSONString());
                        ational_quote_configuration.setConfiguration_type("absolute");
                        map.put("aeop_national_quote_configuration", ational_quote_configuration);
                    }
                }
            }
        }


        //aeop_ae_product_propertys 产品属性
        map.put("aeop_ae_product_propertys", aeAutoProductDto.getCustomAttributesAll());

        map.put("msr_eu_id", aeAutoProductDto.getMsrEuId());


        //营销图和白底图
        map.put("market_images", aeAutoProductDto.getMarketImages());
        //资质信息。注意删除商品资质信息会导致商品不合规被下架处罚，请不要删除商品资质信息
//        map.put("aeop_qualification_struct_list", aeAutoProductDto.getaeop getAeop_qualification_struct_list());
        //商品多媒体信息，该属性主要包含商品的视频列表
//        map.put("aeop_a_e_multimedia", aeAutoProductDto.getm());

        JSONObject json = new JSONObject(map);
        System.out.println("————————————————————————————————————————————");
//        System.out.println(json);
        paremeterMap.put("aeop_a_e_product", json);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.productPost.getCode(),
                        paremeterMap,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg.contains("error_response")) {
            return R.fail(msg);
        } else {
            return R.ok(msg);
        }
    }


    @Override
    public R<Object> productOffline(Long aeProductId, Long storeId) {
        //生成参数Map
        Map<String, Object> map = new HashMap<>();
        map.put("product_ids",aeProductId);
        //获取店铺的accessToken
        String accessToken = AeApiUtils.getToken(storeId);
        String msg =
                AeApiUtils.sendRequest(
                        AliExpressInterfaceEnum.offlineAeProduct.getCode(),
                        map,
                        Protocol.TOP,
                        accessToken
                );
        System.out.println(msg);
        if (msg != null && msg.contains("true")) {
            return R.ok(msg);
        } else {
            return R.fail(msg);
        }
    }




}
